const express = require('express')
const cookieParser = require("cookie-parser");
const session = require("express-session");
const MongoStore = require('connect-mongo');

const app = express()

// 使用解析cookie的中间件
app.use(cookieParser())

app.use(session({
  name: 'sid',  // 设置cookie的name，默认值是：connect.sid
  secret: 'atguigu', // 密钥
  store:MongoStore.create({
		mongoUrl: 'mongodb://127.0.0.1:27017/project' //数据库的连接配置
  }),
  cookie: {
		httpOnly: true, // 开启后前端无法通过 JS 操作
		maxAge: 1000 * 10 // 这一条 是控制 sessionID 的过期时间的！！！
  },
}));

app.use(express.static('public'))
app.use(express.urlencoded({ extended: false }))

const users = [
  {id: 1, username: 'admin', pwd: '111111'},
  {id: 2, username: 'atguigu', pwd: '111111'},
  {id: 3, username: 'xfzhang', pwd: '111111'},
]


app.post('/login2', (req, res) => {
  const {username, pwd} = req.body
  const user = users.find(user => user.username===username && user.pwd===pwd) 
  if (user) {
    console.log('session', req.session)
    // 将用户ID保存到session对象中   , 如果没有session对象, 就会自动创建
    req.session['userId'] = user.id

    res.redirect('/manager2.html')
  } else {
    res.send('登录失败, 用户名或密码错误')
  }
})

app.get('/info2', (req, res) => {
  // 从req的session中得到userId
  console.log(req.session) // 内部就是根据请求携带的sessionid的cookie, 找到对应的session对象
  const userId = req.session['userId']

  const user = users.find(user => user.id==userId) 
  res.send(user)
})


app.post('/login', (req, res) => {
  const {username, pwd} = req.body
  const user = users.find(user => user.username===username && user.pwd===pwd) 
  if (user) {
    // 将用户id以cookie形式交给浏览器保存
    // res.cookie('userId', user.id)  // 会话cookie
    res.cookie('userId', user.id, {
      maxAge: 1000*5,  // 最大存活时间
      httpOnly: true // 不让浏览器修改cookie
    })  // 持久化cookie
    res.cookie('other_key', 'other data', {maxAge: 1000*10}) // 持久化cookie

    res.redirect('/manager.html')
  } else {
    res.send('登录失败, 用户名或密码错误')
  }
})



app.get('/info', (req, res) => {
  // 从req的cookie中得到userId
  console.log(req.cookies)
  const userId = req.cookies['userId']

  const user = users.find(user => user.id==userId) 
  res.send(user)
})

app.listen(5000, () => {
  console.log('服务启动成功! http://localhost:5000')
})
